<script setup name="login">
import { Lock, MessageBox, Tools, UserFilled } from '@element-plus/icons-vue';
import { useStore } from 'vuex';
import { onActivated, onDeactivated, reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { throttle } from 'lodash';
import { CODE_WAIT_TIME } from '@/constants/index.js';
import * as useApi from '@/api/user.js'
import * as strategy from '@/constants/s.js'
import { useRoute, useRouter } from 'vue-router';
const router = useRouter();
const mode = ref('account')
const countDown = ref(CODE_WAIT_TIME);

const form = ref(null)

const account = localStorage.getItem('account') || 'xiaotuxian001';
const password = localStorage.getItem('password') || '123456';
const isRemeber = localStorage.getItem('isRemeber') === 'true' || true;
const mobile = localStorage.getItem('mobile') || '';
const isAgree = ref(false);

const params = reactive({
  account: isRemeber ? account : '',
  password: isRemeber ? password : '',
  isAgree: false,
  isRemeber,
  code: '',
  mobile: isRemeber ? mobile : '',
});
const store = useStore();

function accountChecker(_, value, cb) {
  if (!strategy.ACCOUNT.test(value.trim())) {
    cb(new Error('账号格式错误 应为字母开头 共6-20个字符'));
  } else {
    cb();
  }
}

function mobileChecker(_, value, cb) {
  if (!strategy.MOBILE.test(value.trim())) {
    cb(new Error('手机号格式错误'));
  } else {
    cb();
  }
}

function codeChecker(_, value, cb) {
  if (!strategy.CODE.test(value.trim())) {
    cb(new Error('验证码格式错误'));
  } else {
    cb();
  }
}

function agreeChecker(_, value, cb) {
  if (!value) {
    cb(new Error('不同意不行'));
  } else {
    cb();
  }
}

const rules = reactive({
  account: [{ validator: accountChecker, trigger: 'blur' }],
  mobile: [{ validator: mobileChecker, trigger: 'blur' }],
  code: [{ validator: codeChecker, trigger: 'blur' }],
  isAgree: [{ validator: agreeChecker, trigger: 'change' }],
})

async function login() {
  form.value.validate(async (valid) => {
    if (valid) {
      const res = await store.dispatch('user/login', params);
      if (res.success) {
        // 如果勾选了记住我 就记录相关数据
        if (params.isRemeber) {
          localStorage.setItem('account', params.account);
          localStorage.setItem('password', params.password);
          localStorage.setItem('isMemo', params.isRemeber);
        }
      } else {
        // 失败了清空密码
        params.password = '';
      }
      router.push('/');
    } else {
      return false;
    }
  });
}
// 发送验证码
const sendCode = throttle(() => {
  useApi.getCode(params.value.mobile)
    .then((msg) => {
      ElMessage({
        message: msg,
        type: 'success',
      });
    })
    .catch((msg) => {
      ElMessage({
        message: msg,
        type: 'error',
      });
    });
  countDown.value = CODE_WAIT_TIME - 1;
  const timer = setInterval(() => {
    countDown.value--;
    if (countDown.value < 1) {
      clearInterval(timer);
      countDown.value = CODE_WAIT_TIME;
    }
  }, 1000);
}, CODE_WAIT_TIME * 1000);
// 验证码登录
async function loginCode() {
    await useApi.loginCode({
      mobile: params.value.mobile,
      code: params.value.code
    })
    .then((msg) => {
        ElMessage({
          message: msg,
          type: 'success',
        });
      })
      .catch((msg) => {
        ElMessage({
          message: msg,
          type: 'error',
        });
      });
 }

const useMessage = () => mode.value = 'message'
const useAccount = () => mode.value = 'account'
</script>

<template>
  <!-- 头部 -->
  <header>
    <div class="header-warpper">
      <a href="./" class="header-img"></a>
      <div class="header-right">
        <h2>欢迎登录</h2>
        <a href="./">进入网站首页<el-icon><ArrowRight /></el-icon><el-icon><ArrowRight /></el-icon></a>
      </div>
    </div>
  </header>
  <!-- 主体 -->
  <main>
    <!-- 登录窗口 -->
    <div  class="user">
      <div class="user-nav">
        <button>账户登录</button>
        <button>扫码登录</button>
      </div>
      <el-form
      :model="params"
      ref="form"
      :rules="rules"
      >
      <template v-if="mode === 'account'"
      >
        <div class="user-meg">
          <button @click="useMessage"><el-icon><Message /></el-icon>使用短信登录</button>
        </div >
          <el-form-item prop="account">
            <el-input
              v-model="params.account"
              placeholder="请输入用户名"
              :prefix-icon="UserFilled"
            />
          </el-form-item>
          <el-form-item>
            <el-input
              v-model="params.password"
              placeholder="请输入密码"
              :prefix-icon="Lock"
            />
          </el-form-item>
      </template>
      <template v-else
      >
        <div class="user-meg">
          <button @click="useAccount"><el-icon><Message /></el-icon>使用账号登录</button>
        </div >
          <el-form-item prop="mobile">
            <el-input
              v-model="params.mobile"
              placeholder="请输入手机号"
              :prefix-icon="UserFilled"
            />
          </el-form-item>
          <el-form-item prop="code">
            <el-input
              v-model="params.code"
              placeholder="请输入验证码"
              :prefix-icon="MessageBox"
            >
              <template #append>
                  <el-button
                    @click="sendCode"
                    :disabled="countDown !== CODE_WAIT_TIME"
                  >
                    {{ countDown === CODE_WAIT_TIME ? '发送验证码' : countDown }}
                  </el-button>
              </template>
            </el-input>
          </el-form-item>
      </template>
        <el-form-item>
          <el-checkbox
            v-model="params.isRemeber"
          />
          记住我
        </el-form-item>
        <el-form-item prop="isAgree">
          <el-checkbox
            :class="params.isAgree ?'isAgree':''"
            v-model="params.isAgree"
          />
          我已同意<a href="">《隐私条款》</a>和<a href="">《服务条款》</a>
        </el-form-item>
      </el-form>
      <el-button
        type="primary"
        class="user-login"
        @click="login"
        v-if="mode === 'account'"
      >
        登录
      </el-button>
      <el-button
        type="primary"
        class="user-login"
        @click="loginCode"
        v-else
      >
        登录
      </el-button>
      <div class="user-serve">
        <img src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png" alt="">
        <div>
          <span>忘记密码</span>
          <span>免费注册</span>
        </div>
      </div>
    </div>
  </main>
  <!-- 底部 -->
  <footer>
    <div class="footer-serve">
      <a href="">关于我们</a>
      <a href="">帮助中心</a>
      <a href="">售后服务</a>
      <a href="">配送与验收</a>
      <a href="">商务合作</a>
      <a href="">搜索推荐</a>
      <a href="">友情链接</a>
    </div>
    <div>
      CopyRight © 小兔鲜儿
    </div>
  </footer>
</template>

<style lang="scss" scoped>
  $padding-div: 300px;
  a {
    text-decoration: none;
  }
  header {
    width: 100vw;
    height: 132px;
    .header-warpper {
      width: 100%;
      margin: 20px $padding-div;
      display: flex;
      align-items: center;
      .header-img {
        display: inline-block;
        width: 200px;
        height: 132px;
        background: url(http://erabbit.itheima.net/img/logo.0940ebb5.png) no-repeat center 18px/contain;
        margin-right: 10px;
      }
      .header-right {
        display: flex;
        width: calc(80% - 200px);
        justify-content: space-between;
        align-items: flex-end;
        h2 {
          margin-bottom: 0;
          display: inline-block;
          font-weight: normal;
        }
        a {
          color: #000;
          text-decoration: none;
        }
        .el-icon {
          color: green;
        }
      }
    }
  }

  main {
    height: 488px;
    background: url(http://erabbit.itheima.net/img/login-bg.696efec3.png) no-repeat 50%/cover;
    position: relative;
    .user {
      width: 380px;
      background-color: white;
      height: 400px;
      position: absolute;
      top: 10%;
      right: 25%;
      .user-nav {
        height: 10%;
        border-bottom: 1px solid #ddd;
        button {
          height: 100%;
          width: 50%;
          border: none;
          background-color: transparent;
          font-size: 18px;
        }

      }
      .user-meg {
        margin: 0 10%;
        margin-top: 20px;
        display: flex;
        justify-content: end;
        button {
          color: #27ba9b;
          border: none;
          background-color: transparent;
        }
      }
      .el-form {
        margin: 5px 10%;
        .el-input {
          border: none;
          height: 39px;
          border: 1px solid #cfcdcd;
          width: 100%;
          margin: 5px 0;
        }
        .isAgree {
          --el-checkbox-isAgree-input-border-color: green;
          --el-checkbox-isAgree-bg-color: none;
          --el-checkbox-isAgree-icon-color: green;
        }
        a {
          text-decoration: none;
          color: #069;
        }
      }
      .user-login {
        width: calc(100% - 20%);
        margin: 0 10%;
        height: 40px;
        border: 1px solid #27ba9b;
        border-radius: 0;
        background-color: #27ba9b;
        color: #fff;
      }
      .user-serve {
        margin: 20px 0;
        padding: 0 10%;
        width: calc(100% - 20%);
        display: flex;
        align-items: center;
        justify-content: space-between;
        div {
          color: #aaa;
          font-size: 14px;
          span {
            margin-right: 5px;
          }
        }
      }
    }
  }

  footer {
    margin-top: 60px;
    width: 100%;
    div {
      width: 1240px;
      margin: 0 auto;
      display: flex;
      justify-content: center;
      color: #aaa;
      font-size: 14px;
      margin-bottom: 10px;
    }
    .footer-serve {
      a {
        margin: 5px;
        color: #aaa;
      }
    }
  }
</style>
